<script setup>
import {onMounted, ref} from "vue";

const props = defineProps({
  // 宽度
  width: { type: String, default: '350px' },
  // 高度
  height: { type: String, default: '500px' },
  // axios
  axios: {
    required: true
  },
  // Websocket主机地址
  socketHost: {
    type: String,
    default: window.location.host
  },
  // 根目录
  baseUrl: {
    type: String,
    default: ""
  },
  my: {
    // 我的ID
    id: {
      type: String,
      default: '0',
      required: true
    },
    // 我的token
    token: {
      type: String,
      default: '0'
    },
  },
  friend: {
    // 对方的ID
    id: {
      type: String,
      default: '0',
      required: true
    },
    // 对方名称
    name: {
      type: String,
      required: true,
      default: '空'
    }
  }
})
let websocket = null;
let message = ref("");
const messageList = ref([]);


onMounted(()=>{
  //判断当前浏览器是否支持WebSocket
  if('WebSocket' in window) {
    //改成你的地址
    websocket = new WebSocket("ws://" + props.socketHost + props.baseUrl + "/messageplus/ws/" + props.my.id + "/" + props.my.token);
  } else {
    alert('当前浏览器不支持Websocket！');
  }

  //连接发生错误的回调方法
  websocket.onerror = function() {
    console.log("WebSocket连接发生错误");
  };
  //连接成功建立的回调方法
  websocket.onopen = function() {
    console.log("WebSocket连接成功");
  }
  //接收到消息的回调方法
  websocket.onmessage = function(event) {
    let msg = JSON.parse(event.data);
    messageList.value.push({
      type: 'fri',
      content: msg.data,
      time: new Date(msg.createTime)
    });
  }
  //连接关闭的回调方法
  websocket.onclose = function() {
    console.log("WebSocket连接关闭");
  }
  //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口。
  window.onbeforeunload = function() {
    websocket.close();
  }
})

function sendMessage() {
  if (message.value === "") return;
  props.axios.post('/single/send', message.value, {
    headers: {
     'Content-Type': 'application/json;charset=UTF-8',
     'token': props.my.token
    },
   params:{
    'id1': props.my.id,
    'id2': props.friend.id
   }
  }).then((res)=>{
    messageList.value.push({
      type: 'my',
      content: message.value,
      time:  new Date()
    });
    message.value = "";
    setTimeout(()=>{
      document.getElementById("content").scrollTop = document.getElementById('content').scrollHeight;
    }, 100);
  });
}

// 将timestamp转换为指定字符串格式
function getTime(time, x) {
  const data = time;
  const year = data.getFullYear();
  const month = data.getMonth() + 1;
  const day = data.getDate();
  const hours = data.getHours();
  const minutes = data.getMinutes();
  const seconds = data.getSeconds();
  switch (x) {
    // YY/MM/DD
    case 1:{
      return year+"/"+month+"/"+day;
    }
    // YY/MM/DD HH:mm
    case 2: {
      return year+"/"+month+"/"+day+" "+hours+":"+minutes;
    }
    // YY-MM-DD HH:mm:SS
    case 10: {
      return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
    }
  }
}
</script>
<template>
  <div class="box" :style="{'width': width, 'height': height}">
    <div class="title">{{friend.name}}</div>
    <div id="content" class="content">
      <div style="height: 50px"></div>
      <div id="content_msg">
        <div v-for="msg in messageList">
          <div v-if="msg.type === 'fri'">
            <div class="fri_msg_tim">{{getTime(msg.time, 2)}}</div>
            <div class="fri_msg_con">{{msg.content}}</div>
          </div>
          <div v-else>
            <div class="msg_tim">{{getTime(msg.time, 2)}}</div>
            <div class="msg_con">{{msg.content}}</div>
          </div>
        </div>
      </div>
      <div style="height: 40px"></div>
    </div>
    <div class="inputBox">
      <input type="text" v-model="message">
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>
<style scoped>
.box {
  position: relative;
  border: 1px solid rgba(180,180,180,1);
  background-color: rgba(240,240,240,1);
  padding-top: 40px;
  z-index: 80;
}

.box .title {
  position: absolute;
  top: 0;
  width: 100%;
  text-align: center;
  height: 40px;
  line-height: 40px;
  z-index: 100;
  background-color: rgba(255,255,255,1);
  border-bottom: 1px solid rgba(180,180,180,1);
}

.box .content {
  position: absolute;
  top: 0;
  width: 100%;
  height: calc(100%);
  overflow: auto;
  z-index: 90;
  word-wrap: break-word;
  word-break: normal;
  transition: all 0.5s ease-out;
}

.content .fri_msg_tim {
  height: 15px;
  line-height: 15px;
  margin: 10px;
}

.content .fri_msg_con {
  width: 80%;
  margin: 0 15% 10px 10px;
  padding: 7px;
  background-color: rgba(255,255,255,1);
  border-radius: 5px;
}

.content .msg_tim {
  height: 15px;
  line-height: 15px;
  margin: 10px;
  text-align: right;
}

.content .msg_con {
  width: calc(80% - 10px);
  margin: 0 10px 10px 20%;
  padding: 7px;
  background-color: rgba(35,230,35,1);
  word-wrap: break-word;
  word-break: normal;
  text-align: right;
  border-radius: 5px;
}

.box .inputBox {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 40px;
  background-color: rgba(255,255,255,1);
  z-index: 100;
  border-top: 1px solid rgba(180,180,180,1);
}

.inputBox input {
  width: calc(74% - 20px);
  margin: 8px 10px 8px 10px;
  height: 24px;
  float: left;
  border: 1px solid rgba(180,180,180,1);
}

.inputBox button {
  width: calc(25% - 10px);
  margin: 8px 10px 8px 0;
  height: 24px;
  float: left;
  border: 1px solid rgba(180,180,180,1);
}
.inputBox button:active {
  background-color: rgba(180,180,180,1);
}



/*定义滚动条高宽及背景
 高宽分别对应横竖滚动条的尺寸*/
::-webkit-scrollbar {
  width: 4px;
  background-color: rgba(0,0,0,0);
}
/*定义滚动条轨道
 内阴影+圆角*/
::-webkit-scrollbar-track {
  background-color: rgba(0,0,0,0);
  margin: 40px 0;
}
/*定义滑块
 内阴影+圆角*/
::-webkit-scrollbar-thumb {
  background-color: rgba(200,200,200,0.9);
}

</style>